package com.itheima.jdbc.homework;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：石破天
 * @date ：Created in 2022年09月05日
 * @description ：
 * @version: 1.0
 */
public class QueryAllTest {
   /*
       查询所有学生List<Student> findAllStudent()
          select * from student;
    */
    public static void main(String[] args) throws Exception{
        List<Student> allStudent = findAllStudent();

        System.out.println(allStudent);
    }
    public static List<Student> findAllStudent() throws Exception{
        //1:注册驱动 可以省略
        //2: 获取连接对象
        String url = "jdbc:mysql:///mydb?useSSL=false&useUnicode=true&characterEncoding=utf-8";
        String username="root";
        String password="root";
        Connection conn = DriverManager.getConnection(url, username, password);
        //3: 写sql
        String sql = "select * from student";
        //4:  获取语句执行对象
        Statement state = conn.createStatement();
        //5:  执行sql
        ResultSet rs = state.executeQuery(sql);//调用执行方法才知道sql语句

        ArrayList<Student> list = new ArrayList<>();
        //6:  处理结果内容(集)
        while(rs.next()){
            //解析每一行上 每一个数据
            int sid = rs.getInt("sid");
            String name = rs.getString("name");
            int age = rs.getInt("age");
            Date birthday = rs.getDate("birthday");

            // 完成 学生对象的封装
            Student stu = new Student();
            stu.setSid(sid);
            stu.setName(name);
            stu.setAge(age);
            stu.setBirthday(birthday);
            list.add(stu);
        }
//        System.out.println(list);
        list.forEach(System.out::println);

//        for (Student student : list) {
//            System.out.println(student);
//        }
        //7: 释放资源
        rs.close();
        state.close();
        conn.close();

        return list;
    }
}
